//
//  LogManager.swift
//  position
//
//  Created by HzS on 2023/1/8.
//

import UIKit

func MGFileLogger(_ content: String) {
    LogManager.shared.log(content)
}

final class LogManager: NSObject {
    
    static let shared = LogManager()
    
    let fileHandle: FileHandle
    let filePath: String
    
    let timeFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "HH:mm:ss SSS"
        return formatter
    }()
    
    let dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        return formatter
    }()
    
    override init() {
        var path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
        let time = Date()
        let timeFormatter = DateFormatter()
        timeFormatter.dateFormat = "yyyy-MM-dd"
        let stringTime = timeFormatter.string(from: time)
        path += "/\(stringTime).txt"
        filePath = path
        if !FileManager.default.fileExists(atPath: path) {
            FileManager.default.createFile(atPath: path, contents: "location: [时:分:秒 毫秒, 经度，纬度, speed, horizontalAccuracy, distance, 位置], reason:\n".data(using: .utf8))
        }
        fileHandle = try! FileHandle(forWritingTo: URL(fileURLWithPath: path))
        super.init()
    
        NotificationCenter.default.addObserver(self, selector: #selector(handleAppWillTerminate), name: UIApplication.willTerminateNotification, object: nil)
    }
    
    func log(_ content: String) {
        let content = "\(timeFormatter.string(from: Date())) \(content)\n"
        do {
            if #available(iOS 13.4, *) {
                _ = try fileHandle.seekToEnd()
            } else {
                _ = fileHandle.seekToEndOfFile()
            }
            
            if let data = content.data(using: .utf8) {
                if #available(iOS 13.4, *) {
                    try fileHandle.write(contentsOf: data)
                } else {
                    fileHandle.write(data)
                }
            }
        } catch {
            print("log err: \(error.localizedDescription)")
        }
    }
    
    
    // MARK: - Notification
    
    @objc
    private func handleAppWillTerminate() {
        try? fileHandle.close()
    }
}
